package top.xcxdl.rural.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import top.xcxdl.rural.common.Res;
import top.xcxdl.rural.config.initexception.ErrorEnum;
import top.xcxdl.rural.entity.RuralArea;
import top.xcxdl.rural.entity.RuralProduct;
import top.xcxdl.rural.entity.RuralTab;
import top.xcxdl.rural.service.IRuralAreaService;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Ding
 * @since 2022-05-17
 */
@Api("后台管理产品控制器")
@RestController
@RequestMapping("/admin/area")
public class RuralAreaController {

    @Resource
    private IRuralAreaService service;

    /**
     * 后台获取所有轮播
     * @param pageNo 页码
     * @param pageSize 每页数量
     * @param key 搜索关键字
     * @return 轮播列表
     */
    @ResponseBody
    @GetMapping("/getList")
    @ApiOperation("后台获取所有地域")
    public Res<Object> getList(
            @RequestParam(name = "page_no") Integer pageNo,
            @RequestParam(name = "page_size") Integer pageSize,
            @RequestParam(name = "title",required = false) String key
    ) {
        PageInfo<RuralArea> pageInfo = service.getList(pageNo, pageSize, key);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return Res.success(jsonObject);
    }

    /**
     * 后台新增 or 修改（处理）地域信息
     * @param area 地域实体
     * @return res
     */
    @PostMapping("/doEdit")
    @ApiOperation("后台新增 or 修改（处理）轮播信息")
    @ResponseBody
    public Res<Object> doEdit(
            @RequestBody RuralArea area){
        Integer isNew = area.getAreaId();
        int ret = 0;
        ret += service.doEdit(area);
        return ret > 0 ? Res.success(isNew == null ? "添加成功" : "编辑成功") :
                ret == 0 ? Res.error("操作失败") : Res.error(ErrorEnum.AD_CODE_IS_EXISTS);
    }

    @ApiOperation("后台删除地域")
    @PostMapping("/doDelete")
    @ResponseBody
    public Res<Object> delete(@RequestBody JSONObject jsonObject) {
        //获取id集合
        List<Integer> ids = (List<Integer>) jsonObject.get("ids");
        //删除
        int ret = service.delete(ids);
        return ret > 0 ? Res.success("删除成功") : Res.error("删除失败");
    }

}
